import os
from PIL import Image
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas


# 返回文件名
def file_list(file_dir):

    file_path = []

    for root, dirs, files in os.walk(file_dir):
        for dir1 in dirs:
            file_path.append(os.path.join(root, dir1))

    return file_path


# 文件路径
def file_name(file_dir, suffix=".jpg"):

    file_path = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            # print(file)
            if os.path.splitext(file)[1] == suffix:
                file_path.append(os.path.join(root, file))
    return file_path


def pic_to_pdf(f_pdf, file_dir, suffix):

        (w, h) = landscape(A4)
        c = canvas.Canvas(f_pdf, pagesize=landscape(A4))
        file_ist = file_name(file_dir, suffix)

        for f in file_ist:
            (x_size, y_size) = Image.open(f).size

            # 填满整页
            # c.drawImage(f, 1, 1, w, h)

            rate_rect = h / w
            rate_table = y_size / x_size

            if rate_table >= rate_rect:
                width_x = h / rate_table
                height_y = h
            else:
                width_x = w
                height_y = w * rate_table

            pos_x = (w - width_x) / 2
            pos_y = (h - height_y) / 2

            c.drawImage(f, pos_x, pos_y, width_x, height_y)
            c.showPage()

        c.save()
        print("转换完成")


if __name__ == '__main__':

    # result = file_list("E:\\Programs\\Python\\图片转PDF\\pic")
    # for i in result:
    #     print(i)

    # 1 pdf地址  2 pic地址 3 pic 类型
    pic_to_pdf("E:\\Programs\\Python\\图片转PDF\\pic\\Test.pdf", "E:\\Programs\\Python\\图片转PDF\\pic", ".jpg")

